package com.dormitory.ui;

import com.dormitory.model.CheckIn;
import com.dormitory.model.Room;
import com.dormitory.model.Student;
import com.dormitory.service.CheckInService;
import com.dormitory.service.RoomService;
import com.dormitory.service.StudentService;
import com.dormitory.service.impl.CheckInServiceImpl;
import com.dormitory.service.impl.RoomServiceImpl;
import com.dormitory.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class CheckInPanel extends JPanel {
    private CheckInService checkInService;
    private StudentService studentService;
    private RoomService roomService;
    private JTable checkInTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private JComboBox<Student> studentComboBox;
    private JComboBox<Room> roomComboBox;
    private JTextField checkInDateField;
    private JTextField checkOutDateField;
    private JComboBox<String> statusComboBox;
    private JPanel resultStatsPanel;

    public CheckInPanel() {
        checkInService = new CheckInServiceImpl();
        studentService = new StudentServiceImpl();
        roomService = new RoomServiceImpl();
        initUI();
        loadCheckInData();
    }

    private void initUI() {
        setLayout(new BorderLayout());
        // 工具栏
        JToolBar toolBar = createToolBar();
        add(toolBar, BorderLayout.NORTH);
        
        // 创建结果统计面板
        resultStatsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        resultStatsPanel.setBorder(BorderFactory.createTitledBorder("搜索结果统计"));
        add(resultStatsPanel, BorderLayout.SOUTH);
        
        // 表格
        createTable();
        JScrollPane scrollPane = new JScrollPane(checkInTable);
        add(scrollPane, BorderLayout.CENTER);
    }

    private JToolBar createToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);

        // 搜索框
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> searchCheckIns());

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(e -> showAddDialog());

        // 修改按钮
        JButton editButton = new JButton("修改");
        editButton.addActionListener(e -> showEditDialog());

        // 删除按钮
        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> deleteCheckIn());

        toolBar.add(new JLabel("搜索："));
        toolBar.add(searchField);
        toolBar.add(searchButton);
        toolBar.addSeparator();
        toolBar.add(addButton);
        toolBar.add(editButton);
        toolBar.add(deleteButton);

        return toolBar;
    }

    private void createTable() {
        String[] columnNames = {"入住编号", "学生姓名", "房间号", "入住日期", "退宿日期", "状态"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        checkInTable = new JTable(tableModel);
        checkInTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    private void loadStudents() {
        studentComboBox.removeAllItems();
        List<Student> students = studentService.getAllStudents();
        for (Student student : students) {
            studentComboBox.addItem(student);
        }
    }

    private void loadRooms() {
        roomComboBox.removeAllItems();
        List<Room> rooms = roomService.getAllRooms();
        for (Room room : rooms) {
            roomComboBox.addItem(room);
        }
    }

    private void loadCheckInData() {
        tableModel.setRowCount(0);
        List<CheckIn> checkIns = checkInService.getAllCheckIns();
        for (CheckIn checkIn : checkIns) {
            addCheckInToTable(checkIn);
        }
        // 显示全部数据的统计信息
        updateSearchStats(checkIns, "");
    }

    private void addCheckInToTable(CheckIn checkIn) {
        Student student = studentService.getStudentById(checkIn.getStudentId());
        Room room = roomService.getRoomById(checkIn.getRoomId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        Object[] rowData = {
            checkIn.getCheckInId(),
            student != null ? student.getStudentName() : "未知",
            room != null ? room.getRoomNumber() : "未知",
            checkIn.getCheckInDate() != null ? sdf.format(checkIn.getCheckInDate()) : "",
            checkIn.getCheckOutDate() != null ? sdf.format(checkIn.getCheckOutDate()) : "",
            checkIn.getStatus()
        };
        tableModel.addRow(rowData);
    }

    private void searchCheckIns() {
        String condition = searchField.getText().trim();
        tableModel.setRowCount(0);
        List<CheckIn> checkIns = checkInService.searchCheckIns(condition);
        
        // 更新表格数据
        for (CheckIn checkIn : checkIns) {
            addCheckInToTable(checkIn);
        }
        
        // 更新统计信息
        updateSearchStats(checkIns, condition);
    }

    private void updateSearchStats(List<CheckIn> checkIns, String searchCondition) {
        resultStatsPanel.removeAll();
        
        // 创建统计信息标签
        JLabel totalLabel = new JLabel(String.format("总记录数: %d", checkIns.size()));
        JLabel searchLabel = new JLabel(String.format("搜索条件: %s", searchCondition.isEmpty() ? "全部" : searchCondition));
        
        // 按入住状态统计

        
        // 直接列出所有入住日期（不分组统计）
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dates = checkIns.stream()
            .map(CheckIn::getCheckInDate)
            .filter(date -> date != null)
            .map(formatter::format)
            .collect(Collectors.joining(", "));
        JLabel timeLabel = new JLabel("所有入住日期: " + dates);
        
        // 添加统计信息到面板
        resultStatsPanel.add(totalLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(searchLabel);

        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(timeLabel);
        
        // 刷新面板
        resultStatsPanel.revalidate();
        resultStatsPanel.repaint();
    }

    private void showAddDialog() {
        CheckInFormDialog dialog = new CheckInFormDialog(SwingUtilities.getWindowAncestor(this), null);
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            CheckIn checkIn = dialog.getCheckIn();
            if (checkInService.addCheckIn(checkIn)) {
                JOptionPane.showMessageDialog(this, "添加成功！");
                loadCheckInData();
            } else {
                JOptionPane.showMessageDialog(this, "添加失败！");
            }
        }
    }

    private void showEditDialog() {
        int selectedRow = checkInTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要修改的入住信息！");
            return;
        }
        Integer checkInId = (Integer) tableModel.getValueAt(selectedRow, 0);
        CheckIn checkIn = checkInService.getCheckInById(checkInId);
        if (checkIn == null) {
            JOptionPane.showMessageDialog(this, "未找到入住信息！");
            return;
        }
        CheckInFormDialog dialog = new CheckInFormDialog(SwingUtilities.getWindowAncestor(this), checkIn);
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            CheckIn updated = dialog.getCheckIn();
            updated.setCheckInId(checkInId);
            if (checkInService.updateCheckIn(updated)) {
                JOptionPane.showMessageDialog(this, "修改成功！");
                loadCheckInData();
            } else {
                JOptionPane.showMessageDialog(this, "修改失败！");
            }
        }
    }

    private void deleteCheckIn() {
        int selectedRow = checkInTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的入住信息！");
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this,
            "确定要删除这条入住信息吗？", "确认删除",
            JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            Integer checkInId = (Integer) tableModel.getValueAt(selectedRow, 0);
            if (checkInService.deleteCheckIn(checkInId)) {
                JOptionPane.showMessageDialog(this, "删除成功！");
                loadCheckInData();
            } else {
                JOptionPane.showMessageDialog(this, "删除失败！");
            }
        }
    }

    private void clearForm() {
        studentComboBox.setSelectedIndex(0);
        roomComboBox.setSelectedIndex(0);
        checkInDateField.setText("");
        checkOutDateField.setText("");
        statusComboBox.setSelectedIndex(0);
    }
} 